package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.OriginalProduct;
import com.apes.autoparts.product.repository.OriginalProductDao;
import com.apes.autoparts.product.repository.OriginalProductRepository;
import com.apes.autoparts.product.repository.ProductDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 类描述：原厂标准商品服务类
 *
 * @ClassName originalProductService
 * @Description 描述
 * @Author wushilong
 * @Date 2022/10/9 11:18
 * @Version 1.0
 */
@Service
public class OriginalProductService extends DomainService {

    @Autowired
    OriginalProductRepository originalProductRepository;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private OriginalProductDao originalProductDao;

    /**
     * 批量更新原厂标准商品
     *
     */
    public Map edit(SimpleRequest request){
        //新增和修改
        List<OriginalProduct> originalProductList = request.getA("originalProductItems", OriginalProduct.class);
        Set<String> originalProductSet = new HashSet<>();

        //根据id判断新增
        List<OriginalProduct> newOriginals = originalProductList.stream().filter(original -> Objects.isNull(original.getId()) || "".equals(original.getId()))
                .collect(Collectors.toList());

        //获取删除的数据,如果没有不删除
        if (Objects.nonNull(request.getJO().get("del"))){
            List<OriginalProduct> delOriginalProduct = request.getA("del", OriginalProduct.class);
            delOriginalProduct.forEach(originalProduct -> {
                String sole = originalProduct.getName() + originalProduct.getOeMark() + originalProduct.getEpcVersion();
                if (Objects.nonNull(originalProduct.getId()) && originalProductSet.add(sole)){
                    originalProductRepository.delete(originalProduct);
                }
            });
        }

        //保存并返回
        productDao.originalInsert(newOriginals);
        return  MapUtil.mapper("originalProductItems", newOriginals);

    }

    /**
     * 放弃编辑回显当前数据
     * @param request
     * @return
     */
    public Map originalProductFindOne(SimpleRequest request){
        JSONArray array = request.get("originalProductItems");
        return MapUtil.mapper("originalProductItems",array);
    }



    /**
     * 动态条件查询
     * @param request
     *//*
    public Map conditionQuery2(SimpleRequest request){
        JSONObject jo = request.getJO();
            String name = jo.getString("name");
            String oeMark = jo.getString("oeMark");
            String epcVersion = jo.getString("epcVersion");
        int page = jo.getInteger("page") < 0 ? 0 : jo.getInteger("page");

        if (Objects.isNull(name) && Objects.isNull(oeMark) && Objects.isNull(epcVersion)) {
            Page<OriginalProduct> originalPage = originalProductRepository.findAll(PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", originalPage.getContent(), "page", page, "sum", originalPage.getTotalPages());
        }
        Page<OriginalProduct> originalPage = originalProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "EQ", name,
                "oeMark", "EQ", oeMark,
                "epcVersion", "EQ", epcVersion),
                PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", originalPage.getContent(), "page", page, "sum", originalPage.getTotalPages());

    }*/

    /**
     * 动态条件查询
     * @param request
     */
    public Map conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject jsonObject =  (JSONObject) originalProductDao.countOrigin(jo).get(0);
        Integer count = jsonObject.getInteger("COUNT");
        Integer page = jo.getInteger("page");
        Integer size = jo.getInteger("size");
        if(size>count){
            size = count;
            page = count-50;
        }
        if(page<0){
            page=0;
            size=50;
        }
        JSONArray array = originalProductDao.findAllOrigin(jo,page,size);
        return  MapUtil.mapper("content", array, "page", page, "size",size,"sum",count);
    }




    /**
     * 导出下载
     * @param request
     * @return
     */
    public Map download(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        String name = condition.getString("name");
        String epcVersion = condition.getString("epcVersion");
        String oeMark = condition.getString("oeMark");
        if("".equals(name)){
            name=null;
        }
        if("".equals(epcVersion)){
            epcVersion=null;
        }
        if("".equals(oeMark)){
            oeMark=null;
        }

        Page<OriginalProduct> page = originalProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("name", "EQ", name,
                "epcVersion", "EQ", epcVersion,
                "oeMark", "EQ", oeMark),
                PageRequest.of(request.get("page"), request.get("size"), Sort.by(Sort.Direction.DESC, "id")));
        return MapUtil.mapper("content", page.getContent(), "total", page.getTotalElements(), "pages", page.getTotalPages(), "page", request.get("page"));
    }

    /**
     * 批量删除
     *
     * @param request
     * @return
     */
    public Map delOriginal(SimpleRequest request){
        List<OriginalProduct> delOriginalProduct = request.getA("del", OriginalProduct.class);
        for (OriginalProduct originalProduct : delOriginalProduct) {
            originalProductRepository.delete(originalProduct);
        }

        request.setBody(request.getJO().getString("model"));
        return conditionQuery(request);
    }



    /**
     * 编辑原厂标准商品
     * @param request
     * @return
     */
    public OriginalProduct updateOriginalProduct(SimpleRequest request){
        OriginalProduct neworigin = request.getJO().getObject("origin", OriginalProduct.class);
        OriginalProduct orining = originalProductRepository.findOne(neworigin.getId());
        orining.setEpcVersion(neworigin.getEpcVersion());
        orining.setOeMark(neworigin.getOeMark());
        orining.setName(neworigin.getName());
        return originalProductRepository.saveAndFlush(orining);
    }
    /**
     * 添加原厂标准商品
     * @param request
     * @return
     */
    public OriginalProduct insertOriginal(SimpleRequest request){
        JSONObject jo = request.getJO();
        OriginalProduct orining  = jo.getObject("data",OriginalProduct.class);
        try{
            orining =   originalProductRepository.saveAndFlush(orining);
            return orining;
        }catch (Exception e) {
            throw new RuntimeException("添加失败，原件件号加EPC版本号不能重复！");
        }
    }




    /**
     * 定制导入原厂标准商品
     * @param request
     * @return
     */
    public JSONObject importOriginalProduct(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        String key = appendImportReturn_New(importData, titleColumnArray);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();

        JSONArray titleArray = new JSONArray(3);
        titleArray.add("EPC版本号");
        titleArray.add("原件件号");
        titleArray.add("标准名称");
        titleColumnArray.add(titleArray);

        List<OriginalProduct> dataList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            importDataValueArray.parallelStream().forEach( item -> {
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() <3) return;
                String epcVersion = "";
                String oeMark = "";
                String name = "";
                OriginalProduct originalProduct = new OriginalProduct();
                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0:
                            epcVersion = iValueArray.getString(0);
                            break;
                        case 1:
                            oeMark = iValueArray.getString(1);
                            break;
                        case 2:
                            name = iValueArray.getString(2);
                            break;
                    }
                }

                if ("原件件号".equals(oeMark) && "EPC版本号".equals(epcVersion)) {    // 匹配中英文
                    return;
                }
                Map<String,String> map = originalProductRepository.queryByCondition(oeMark,epcVersion);

                if (!stringHashSet.add(name + oeMark + epcVersion)) throw new RuntimeException("导入重复数据，请重新导入！");

                originalProduct.setEpcVersion(epcVersion);
                originalProduct.setOeMark(oeMark);
                originalProduct.setName(name);

                dataList.add(originalProduct);
            });
        });
        productDao.originalInsert(dataList);
        return key.get();
    }


    /**
     * 根据车牌获取EPC版本号
     * 根据EPC版本号和OE号匹配商品
     * @param request
     * @return
     */
    public List getEPC(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        String automobile = requestJO.getString("automobile");
        String oe = requestJO.getString("oe");
        List<Map<String, String>> epc = originalProductDao.getEPC(automobile);
        List<String> epc_bbmc = epc.stream().map(item -> item.get("EPC_BBMC")).collect(Collectors.toList());
        return originalProductDao.comparison(oe, epc_bbmc);
    }

    /**
     * 供应商商品状态重新审核
     * @param request
     */
    public String matching(SimpleRequest request){
        Map map = new HashMap();
        JSONObject jsonObject =   JSON.parseObject(invoke("sp.spProduct.anewMatching",map));
        return jsonObject.getString("body");
    }

}
